package com.bzsg.simpleMediaPlayer.ui.pager.video

import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.ViewGroup
import android.view.ViewTreeObserver
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Fullscreen
import androidx.compose.material.icons.filled.FullscreenExit
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.bzsg.simpleMediaPlayer.data.PlayerState
import com.bzsg.simpleMediaPlayer.viewModel.PlayerViewModel
import com.bzsg.simpleMediaPlayer.viewModel.VideoStateViewModel

@Composable
@Preview
fun VideoPlayerScreen(
    videoStateViewModel: VideoStateViewModel = hiltViewModel(),
    playerViewModel: PlayerViewModel = hiltViewModel(),
) {
    val fullScreenState = rememberFullScreenState()
    val uiState by playerViewModel.playerState.collectAsStateWithLifecycle()
    var text = @Composable { modifier: Modifier ->
        when (val state = uiState) {
            is PlayerState.Idle -> Text("idle")
            is PlayerState.Initialized -> Text(modifier = modifier, text = "Initialized")
            is PlayerState.Prepared -> {
                state.resolution
                Text(modifier = modifier, text = "Prepared")
            }

            is PlayerState.Playing -> Text(modifier = modifier, text = "Playing")
            is PlayerState.Paused -> Text(modifier = modifier, text = "Paused")
            is PlayerState.Seeking -> Text(modifier = modifier, text = "Seeking")
            is PlayerState.Completed -> Text(modifier = modifier, text = "Completed")
            is PlayerState.Stopped -> Text(modifier = modifier, text = "Stopped")
            is PlayerState.Error -> Text(modifier = modifier, text = "Error")
        }
    }
    LaunchedEffect(videoStateViewModel.isFullScreen) {
        if (videoStateViewModel.isFullScreen) {
            fullScreenState.enterFullScreen()
        } else {
            fullScreenState.exitFullScreen()
        }
    }
    // 定义可复用的视频表面
    val videoSurface = @Composable { modifier: Modifier ->
        VideoSurface(
            modifier = modifier,
            videoStateViewModel = videoStateViewModel,
            playerViewModel = playerViewModel
        )
    }

    // 根据状态切换布局（集成状态文本）
    if (videoStateViewModel.isFullScreen) {
        FullScreenPlayer(
            onExitFullScreen = { videoStateViewModel.toggleFullScreen() },
            videoSurface = videoSurface,
            statusText = text // 添加状态文本参数
        )
    } else {
        HalfScreenPlayer(
            onEnterFullScreen = { videoStateViewModel.toggleFullScreen() },
            videoSurface = videoSurface,
            playerViewModel=playerViewModel,
            playerState = uiState,
            statusText = text // 添加状态文本参数
        )
    }
}

// 竖屏半屏播放器
@Composable
fun HalfScreenPlayer(
    onEnterFullScreen: () -> Unit,
    videoSurface: @Composable (Modifier) -> Unit,
    playerViewModel: PlayerViewModel,
    playerState: PlayerState,
    statusText: @Composable (Modifier) -> Unit,
) {
    Column(
        modifier =
            Modifier
                .fillMaxWidth()
                .fillMaxHeight()
    ) {
        videoSurface(
            Modifier
                .fillMaxWidth()
                .aspectRatio(16f / 9f)
        )
        IconButton(
            onClick = onEnterFullScreen,
            modifier =
                Modifier
                    .align(Alignment.End)
                    .background(Color(0xFFD0BCFF)),
        ) {
            Icon(
                imageVector = Icons.Default.Fullscreen,
                contentDescription = "全屏",
            )
        }
        IconButton(
            onClick = {
                 if(playerState is PlayerState.Playing){
                      playerViewModel.pause()
                 }else if(playerState is PlayerState.Paused){
                     playerViewModel.resume()
                 }
            },
            modifier =
                Modifier
                    .align(Alignment.Start)
                    .background(Color(0xFFD0BCFF)),
        ) {
            Icon(
                imageVector = Icons.Default.Fullscreen,
                contentDescription = "暂停",
            )
        }

        var isSeeking by remember { mutableStateOf(false) }
        var tempPosition by remember { mutableStateOf(0f) }

        Slider(
            value = if (isSeeking) tempPosition else playerViewModel.currentPosition.toFloat(),
            onValueChange = { newValue ->
                isSeeking = true
                tempPosition = newValue
            },
            onValueChangeFinished = {
                playerViewModel.seekTo(tempPosition)
                isSeeking = false
            },

            valueRange = 0f..playerViewModel.totalDuration.toFloat()
        )
        statusText(
            Modifier.background(
                color = Color.Red,
            )
        )
    }

}

// 横屏全屏播放器
@Composable
fun FullScreenPlayer(
    onExitFullScreen: () -> Unit,
    videoSurface: @Composable (Modifier) -> Unit,
    statusText: @Composable (Modifier) -> Unit,
) {
    Box(
        modifier =
            Modifier
                .fillMaxSize(),
    ) {
        // 视频播放区域（全屏）
        // 退出全屏按钮
        videoSurface
        IconButton(
            onClick = onExitFullScreen,
            modifier =
                Modifier
                    .align(Alignment.TopEnd)
                    .padding(16.dp),
        ) {
            Icon(
                imageVector = Icons.Default.FullscreenExit,
                contentDescription = "退出全屏",
                tint = Color.White,
            )
        }
    }
}

// 视频播放表面（示例）
@Composable
fun VideoSurface(
    modifier: Modifier = Modifier,
    videoStateViewModel: VideoStateViewModel,
    playerViewModel: PlayerViewModel
) {
    val context = LocalContext.current

    // 1. 使用 remember 保持稳定实例
    val surfaceView = remember {
        SurfaceView(context)
    }

    DisposableEffect(Unit) {
        val callback = object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
                playerViewModel.setSurface(holder.surface, context.assets)
            }

            override fun surfaceChanged(
                holder: SurfaceHolder,
                format: Int,
                width: Int,
                height: Int
            ) {
                playerViewModel.changeSurface(
                    width,
                    height,
                    videoStateViewModel.isFullScreen
                )
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {
                Log.i("VideoSurface", "Surface destroyed")
            }
        }

        // 添加回调
        surfaceView.holder.addCallback(callback)

        // 清理资源
        onDispose {
            surfaceView.holder.removeCallback(callback)
        }
    }

    // 3. 尺寸变化监听器
    DisposableEffect(surfaceView) {
        val listener = ViewTreeObserver.OnGlobalLayoutListener {
            val width = surfaceView.width
            val height = surfaceView.height
            if (width > 0 && height > 0) {
                playerViewModel.changeSurface(
                    width,
                    height,
                    videoStateViewModel.isFullScreen
                )
            }
        }

        surfaceView.viewTreeObserver.addOnGlobalLayoutListener(listener)

        onDispose {
            surfaceView.viewTreeObserver.removeOnGlobalLayoutListener(listener)
        }
    }

    // 4. 使用 AndroidView 嵌入（不参与重组）
    AndroidView(
        factory = { surfaceView },
        modifier = modifier
            .onSizeChanged { layoutSize ->
                // 5. 更新视图尺寸而不触发重组
                surfaceView.layoutParams = ViewGroup.LayoutParams(
                    layoutSize.width,
                    layoutSize.height
                )
            }
    )
}

